#include "mainwindow.h"
#include "loginwindow.h"
#include <QApplication>

MainWindow::MainWindow(const QString &username, Database *db, QWidget *parent)
    : QMainWindow(parent)
    , username(username)
    , db(db)
{
    setupUI();
    createConnections();
}

MainWindow::~MainWindow()
{
}

void MainWindow::setupUI()
{
    setWindowTitle("图书管理系统 - 主界面");
    resize(800, 600);

    centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);

    mainLayout = new QVBoxLayout(centralWidget);
    mainLayout->setSpacing(0);
    mainLayout->setContentsMargins(0, 0, 0, 0);

    // 顶部工具栏
    QWidget *toolbar = new QWidget(this);
    toolbar->setStyleSheet("background-color: #2196F3;");
    toolbar->setFixedHeight(60);

    QHBoxLayout *toolbarLayout = new QHBoxLayout(toolbar);
    toolbarLayout->setContentsMargins(20, 0, 20, 0);

    // 欢迎信息
    QLabel *welcomeLabel = new QLabel(QString("欢迎, %1").arg(username), this);
    welcomeLabel->setStyleSheet("color: white; font-size: 16px;");
    toolbarLayout->addWidget(welcomeLabel);

    // 按钮
    bookManagementButton = new QPushButton("图书管理", this);
    userInfoButton = new QPushButton("我的信息", this);
    logoutButton = new QPushButton("退出登录", this);

    QString buttonStyle = "QPushButton { color: white; padding: 8px 16px; border: none; border-radius: 4px; }"
                         "QPushButton:hover { background-color: rgba(255, 255, 255, 0.2); }"
                         "QPushButton:pressed { background-color: rgba(255, 255, 255, 0.3); }";

    bookManagementButton->setStyleSheet(buttonStyle);
    userInfoButton->setStyleSheet(buttonStyle);
    logoutButton->setStyleSheet(buttonStyle);

    toolbarLayout->addWidget(bookManagementButton);
    toolbarLayout->addWidget(userInfoButton);
    toolbarLayout->addWidget(logoutButton);

    mainLayout->addWidget(toolbar);

    // 内容区域
    stackedWidget = new QStackedWidget(this);
    bookManagement = new BookManagement(db, this);
    userInfo = new UserInfo(username, db, this);

    stackedWidget->addWidget(bookManagement);
    stackedWidget->addWidget(userInfo);

    mainLayout->addWidget(stackedWidget);

    // 设置窗口样式
    setStyleSheet("QMainWindow { background-color: white; }");
}

void MainWindow::createConnections()
{
    connect(bookManagementButton, &QPushButton::clicked, this, &MainWindow::onBookManagementClicked);
    connect(userInfoButton, &QPushButton::clicked, this, &MainWindow::onUserInfoClicked);
    connect(logoutButton, &QPushButton::clicked, this, &MainWindow::onLogoutClicked);
}

void MainWindow::onBookManagementClicked()
{
    stackedWidget->setCurrentWidget(bookManagement);
}

void MainWindow::onUserInfoClicked()
{
    stackedWidget->setCurrentWidget(userInfo);
}

void MainWindow::onLogoutClicked()
{
    LoginWindow *loginWindow = new LoginWindow(this->db);
    loginWindow->show();
    this->close();
} 
